/* main.c -- Battlefield: Bad Company 2 .so loader
 *
 * Copyright (C) 2021 Andy Nguyen
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include <psp2/apputil.h>
#include <psp2/io/dirent.h>
#include <psp2/kernel/threadmgr.h>
#include <psp2/system_param.h>
#include <psp2/ctrl.h>
#include <psp2/power.h>
#include <psp2/touch.h>

#include "main.h"
#include "config.h"
#include "dialog.h"
#include "so_util.h"
#include "jni.h"
#include "utils.h"
#include "dynlib.h"
#include "patch/patch.h"

int _newlib_heap_size_user = MEMORY_NEWLIB_MB * 1024 * 1024;

so_module so_mod;

int main_thread(SceSize args, void *argp)
{
	int (*SDL_Main)(int a1, char **a2) = (void *)so_symbol(&so_mod, "SDL_main");
	SDL_Main(0, NULL);

	return 0;
}

int main(int argc, char *argv[])
{
	sceIoRemove(LOG_PATH);
	sceIoMkdir(GAME_SAVE_PATH, 0777);
	sceIoMkdir(GAME_CACHE_PATH, 0777);
	sceIoMkdir(GAME_SETTING_PATH, 0777);

	scePowerSetArmClockFrequency(444);
	scePowerSetBusClockFrequency(222);
	scePowerSetGpuClockFrequency(222);
	scePowerSetGpuXbarClockFrequency(166);

	SceAppUtilInitParam init_param;
	SceAppUtilBootParam boot_param;
	memset(&init_param, 0, sizeof(SceAppUtilInitParam));
	memset(&boot_param, 0, sizeof(SceAppUtilBootParam));
	sceAppUtilInit(&init_param, &boot_param);

	sceAppUtilSystemParamGetInt(SCE_SYSTEM_PARAM_ID_LANG, &language);
	sceAppUtilSystemParamGetInt(SCE_SYSTEM_PARAM_ID_ENTER_BUTTON, &enter_button);

	sceCtrlSetSamplingModeExt(SCE_CTRL_MODE_ANALOG_WIDE);
	sceTouchSetSamplingState(SCE_TOUCH_PORT_FRONT, SCE_TOUCH_SAMPLING_STATE_START);
	SDL_setenv("VITA_DISABLE_TOUCH_BACK", "1", 1);

	if (check_kubridge() < 0)
		fatal_error("Error kubridge.skprx is not installed.");

	if (!file_exists("ur0:/data/libshacccg.suprx") && !file_exists("ur0:/data/external/libshacccg.suprx"))
		fatal_error("Error libshacccg.suprx is not installed.");

	if (so_load(&so_mod, SO_PATH_0, LOAD_ADDRESS) < 0)
	{
		if (so_load(&so_mod, SO_PATH_1, LOAD_ADDRESS) < 0)
			fatal_error("Error could not load %s.", SO_PATH_1);
	}

	so_relocate(&so_mod);
	so_resolve(&so_mod, dynlib_functions, getNumberOfDynlibFunctions(), 1);

	patch_game();
	so_flush_caches(&so_mod);

	so_initialize(&so_mod);

	init_jni();

	SceUID thid = sceKernelCreateThread("main_thread", (SceKernelThreadEntry)main_thread, 0x40, 128 * 1024, 0, 0, NULL);
	sceKernelStartThread(thid, 0, NULL);
	return sceKernelExitDeleteThread(0);
}
